package cn.edu.buu.hospital.service.impl;

import cn.edu.buu.hospital.entity.Appointment;
import cn.edu.buu.hospital.entity.Department;
import cn.edu.buu.hospital.entity.User;
import cn.edu.buu.hospital.entity.Visit;
import cn.edu.buu.hospital.entity.Doctor;
import cn.edu.buu.hospital.service.DoctorService;
import cn.edu.buu.hospital.mapper.VisitMapper;
import cn.edu.buu.hospital.service.AppointmentService;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.UserService;
import cn.edu.buu.hospital.service.VisitService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class VisitServiceImpl implements VisitService {

    @Autowired
    private VisitMapper visitMapper;
    
    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private UserService userService;

    @Autowired
    private AppointmentService appointmentService;
    
    @Autowired
    private DoctorService doctorService;
    
    @Override
    public void add(Visit visit) {
        // 参数验证
        if (visit == null) {
            throw new IllegalArgumentException("排班信息不能为空");
        }
        if (visit.getUserId() == null) {
            throw new IllegalArgumentException("医生ID不能为空");
        }
        if (visit.getDeptId() == null) {
            throw new IllegalArgumentException("科室ID不能为空");
        }
        if (visit.getVisitPeriod() == null || visit.getVisitPeriod().isEmpty()) {
            throw new IllegalArgumentException("排班时段不能为空");
        }
        if (visit.getMaxNum() == null || visit.getMaxNum() <= 0) {
            throw new IllegalArgumentException("可预约数量必须大于0");
        }
        
        // 确保createTime已设置
        if (visit.getCreateTime() == null) {
            visit.setCreateTime(LocalDateTime.now());
        }
        
        // 确保usedNum已设置
        if (visit.getUsedNum() == null) {
            visit.setUsedNum(0);
        }
        
        visitMapper.insert(visit);
    }

    @Override
    public void removeById(Long visitId) {
        // 先删除相关的预约记录
        List<Appointment> appointments = appointmentService.findByVisitId(visitId);
        for (Appointment appointment : appointments) {
            appointmentService.removeById(appointment.getAppointmentId());
        }
        // 再删除排班记录
        visitMapper.deleteById(visitId);
    }

    @Override
    public void modify(Visit visit) {
        visitMapper.update(visit);
    }

    @Override
    public Visit findById(Long visitId) {
        Visit visit = visitMapper.selectById(visitId);
        // 填充科室和医生信息
        if (visit != null) {
            fillVisitDetails(visit);
        }
        return visit;
    }

    @Override
    public List<Visit> findAll() {
        List<Visit> visitList = visitMapper.selectAll();
        // 填充科室和医生信息
        for (Visit visit : visitList) {
            fillVisitDetails(visit);
        }
        return visitList;
    }

    @Override
    public PageInfo<Visit> find(int pageNum, int pageSize, Visit condition) {
        PageHelper.startPage(pageNum, pageSize);
        List<Visit> visitList = visitMapper.selectByCondition(condition);
        
        // 填充科室和医生信息
        for (Visit visit : visitList) {
            fillVisitDetails(visit);
        }
        
        return new PageInfo<>(visitList);
    }
    
    @Override
    public List<Visit> findByDeptId(Long deptId) {
        Visit condition = new Visit();
        condition.setDeptId(deptId);
        List<Visit> visitList = visitMapper.selectByCondition(condition);
        for (Visit visit : visitList) {
            fillVisitDetails(visit);
        }
        return visitList;
    }
    
    @Override
    public void updateUsedNum(Long visitId) {
        visitMapper.updateUsedNum(visitId);
    }
    
    /**
     * 填充排班的科室和医生信息
     */
    private void fillVisitDetails(Visit visit) {
        // 填充科室信息
        if (visit.getDeptId() != null) {
            Department department = departmentService.findById(visit.getDeptId());
            if (department != null) {
                visit.setDepartment(department);
            }
        }
        
        // 填充医生姓名 - 先尝试从doctor表中查找
        if (visit.getUserId() != null) {
            // 首先尝试从doctor表中查询医生信息
            Doctor doctor = doctorService.findById(visit.getUserId());
            if (doctor != null && doctor.getDoctorName() != null && !doctor.getDoctorName().isEmpty()) {
                visit.setDoctorName(doctor.getDoctorName());
            } else {
                // 如果在doctor表中找不到，则尝试从user表中查询
                User user = userService.findById(visit.getUserId());
                if (user != null && user.getUsername() != null && !user.getUsername().isEmpty()) {
                    visit.setDoctorName(user.getUsername());
                } else {
                    visit.setDoctorName("未知医生");
                }
            }
        } else {
            visit.setDoctorName("未知医生");
        }
    }
}